<?php

class User_MobileController extends Ac_Controller_Action
{
    /**
     * 
     */
    public function init()
    {
        /* Initialize action controller here */
        if(!empty($this->loggedin_user)){
            $this->view->user= $this->loggedin_user;
        }
    }

    /**
     *
     */
    public function indexAction()
    {
        $this->addTitle('account Admin');
        if(empty($this->loggedin_user)){
            //raise an exception
            throw new Exception("Must be logged in to access User Dashboard");
        }
        
        $this->view->getNoPublishedAds = $this->loggedin_user->getNoPublishedAds();
        $this->view->getNoViews = $this->loggedin_user->getNoViews();
        $this->view->getNoShares = $this->loggedin_user->getNoShares();
        $this->view->getNoResponses = $this->loggedin_user->getNoResponses();
        $this->view->subAccounts = '7';        
    }
    
    /**
     *
     */
	public function savedAction()
	{
		if(empty($this->loggedin_user)){
			$mobilespace = new Zend_Session_Namespace('Mobile');
            $mobilespace->back_url2 = $this->view->geturl('saved', 'user');
            $this->_redirect($this->view->geturl('login', 'user'));
        }        
        
        $this->_helper->_layout->setLayout('layout-mobile2');
        
        $this->view->bookmark = $this->getBookmarkSortAction();
        
        $this->render('saved');
	}
	
	/**
     *
     */
	public function viewedAction()
	{
        $this->_helper->_layout->setLayout('layout-mobile2');
        
        if (!empty($_GET['hid'])) {
        	$uniqid = $_COOKIE['ac_bookmark'];
			Model_History::remove(array('ls'=>new MongoID($_GET['hid']), 'uid'=>$uniqid));
        }
        
        $this->view->bookmark = $this->getHistorySortAction();
        
        $this->render('viewed');
	}
	
	public function getHistorySortAction()
    {
    	$page = empty($_GET['page'])?'1':$_GET['page'];
    	$count = 0;
    	$res = array();
    	$list = Model_History::getMobileList();
    	if(!empty($list))
    	{
			foreach ($list as $bmk) 
			{
				$item = $bmk->listing;
				//echo (string)$bmk->_id."->".$item->title."->".$item->id."->".$bmk->created_at."<br>";
				if (empty($item)){
					//echo (string)$bmk->_id."->".$item->title."->".$item->id."->".$bmk->created_at."<br>";exit();
					Model_History::remove(array('_id'=>$bmk->_id));
					continue;
				}
				$count++;
			}
			$this->view->count = $count;
			$lists = Model_History::getMobileList()->limit(10)->sort(array('c_dt'=>-1))->skip(($page-1)*10);
			foreach($lists as $bmks)
			{
				//echo "<br>".$val->id." ".date('j M Y', $val->posted_at)." ".$val->price." ".$val->url();
				$val = $bmks->listing;
				//Define the price value
			    $price = '';
			    $price1 = "";
			    $price2 = "";
			    $location = "";
			    if (!empty($val->sale_price) || !empty($val->rent_price)){
			        if (!empty($val->sale_price)) {
			            $sale_price = number_format($val->sale_price);
			            $price1 = "<dd>HKD ".$sale_price."<em>".$this->view->t('(Sale)')."</em></dd>";
			        }
			        if (!empty($val->rent_price)) {
			            $rent_price = number_format($val->rent_price);
			            $price2 = "<dd>HKD ".$rent_price."<em>".$this->view->t('(Rent)')."</em></dd>";
			        }
			        $price = $price1.' '.$price2;
			    }
			    elseif (!empty($val->is_free)){
			        $price = $this->view->t('Free');
			    }
			    elseif (!empty($val->is_contact)){
			        $price = $this->view->t('Please contact');
			    }
			    elseif (!empty($val->price)){
			        $price = 'HKD '.number_format($val->price);
			    }
				if(!empty($val->area_l2))
					$location = $val->area_l2;
					
				//for SOLD items
				$sold = "";
				if($val->sold){
					$sold = Zend_Registry::get('Zend_View')->t("Sold");
				}
					
			    $res[] = array(
			        'id' => (string) $val->_id,
			        'url' => $val->url(),
			        'title' => $val->title,
			        'photo' => $this->view->thumbnail()->scale($val->featured_photo, 80, 80),
			        //'price' => 'HKD '.number_format($listing->price),
			        'price' => $price,
			        'url' => $val->url(),
			        'posted' => date('j M Y', $val->posted_at),
			        'location' => $location,
			        'sold'=> $sold,
			    );
			}
			//echo "<pre>";print_r($res);echo "</pre>";
		}
		/*{
	    	foreach($list as $bmk) 
				$count++;
			$this->view->count = $count;
	        $page = empty($_GET['page'])?'1':$_GET['page'];
	        $list = Model_History::getMobileList()->skip(($page-1)*10)->limit(10)->sort(array('created_at'=>-1));
	        
	        $count = 0;
	        foreach($list as $bmk) {
	            $listing = $bmk->listing;
	            if (empty($listing)){
	                //$bmk->deleteListing();
	                continue;
	            }
	            $count++;
	            if ($count>10) {
	                break;
	            }
	
	            //Define the price value
			    $price = '';
			    $price1 = "";
			    $price2 = "";
			    $location = "";
			    if (!empty($listing->sale_price) || !empty($listing->rent_price)){
			        if (!empty($listing->sale_price)) {
			            $sale_price = number_format($listing->sale_price);
			            $price1 = "<dd>HKD ".$sale_price."<em>(Sale)</em></dd>";
			        }
			        if (!empty($listing->rent_price)) {
			            $rent_price = number_format($listing->rent_price);
			            $price2 = "<dd>HKD ".$rent_price."<em>(Rent)</em></dd>";
			        }
			        $price = $price1.' '.$price2;
			    }
			    elseif (!empty($listing->is_free)){
			        $price = 'Free';
			    }
			    elseif (!empty($listing->is_contact)){
			        $price = 'Please contact';
			    }
			    elseif (!empty($listing->price)){
			        $price = 'HKD '.number_format($listing->price);
			    }
				if(!empty($listing->district))
					$location = $listing->district;
	            
	            $res[] = array(
			        'id' => (string) $listing->_id,
			        'url' => $listing->url(),
			        'title' => $listing->title,
			        'photo' => $this->view->thumbnail()->scale($listing->featured_photo, 80, 80),
			        //'price' => 'HKD '.number_format($listing->price),
			        'price' => $price,
			        'url' => $listing->url(),
			        'posted' => date('j M Y', $listing->posted_at),
			        'location' => $location,
			        //'count'=> $list->count(),
			    );
	        }
	    }*/
        //$this->_helper->json(array('list' => $res, 'count' => $list->count()));
        return $res;
    }
	
	/**
     *Get saved listings that includes sorting
     */
    public function getBookmarkSortAction()
    {
		$page = empty($_GET['page'])?'1':$_GET['page'];
		$sort = empty($_GET['sort'])?array('p_dt'=>-1):$_GET['sort'];
		$list = Model_Bookmark::getList()->sort(array('c_dt'=>-1));
		$count = 0;
		$arr_bmk = array();
		$res = array();
		if(!empty($list))
		{
			foreach ($list as $bmk) 
			{
				$item = $bmk->listing;
				//echo (string)$bmk->_id."->".$item->title."->".$item->id."->".$bmk->created_at."<br>";
				if (empty($item)){
					Model_Bookmark::remove(array('_id'=>$bmk->_id));
					continue;
				}
				$count++;
			}
			$this->view->count = $count;
			$lists = Model_Bookmark::getList()->limit(10)->sort(array('c_dt'=>-1))->skip(($page-1)*10);
			foreach($lists as $bmks)
			{
				//echo "<br>".$val->id." ".date('j M Y', $val->posted_at)." ".$val->price." ".$val->url();
				$val = $bmks->listing;
				//Define the price value
			    $price = '';
			    $price1 = "";
			    $price2 = "";
			    $location = "";
			    if (!empty($val->sale_price) || !empty($val->rent_price)){
			        if (!empty($val->sale_price)) {
			            $sale_price = number_format($val->sale_price);
			            $price1 = "<dd>HKD ".$sale_price."<em>".$this->view->t('(Sale)')."</em></dd>";
			        }
			        if (!empty($val->rent_price)) {
			            $rent_price = number_format($val->rent_price);
			            $price2 = "<dd>HKD ".$rent_price."<em>".$this->view->t('(Rent)')."</em></dd>";
			        }
			        $price = $price1.' '.$price2;
			    }
			    elseif (!empty($val->is_free)){
			        $price = $this->view->t('Free');
			    }
			    elseif (!empty($val->is_contact)){
			        $price = $this->view->t('Please contact');
			    }
			    elseif (!empty($val->price)){
			        $price = 'HKD '.number_format($val->price);
			    }
				if(!empty($val->area_l2))
					$location = $val->area_l2;
					
				//for SOLD items
				$sold = "";
				if($val->sold){
					$sold = "Sold";
				}
				
			    $res[] = array(
			        'id' => (string) $val->_id,
			        'url' => $val->url(),
			        'title' => $val->title,
			        'photo' => $this->view->thumbnail()->scale($val->featured_photo, 80, 80),
			        //'price' => 'HKD '.number_format($listing->price),
			        'price' => $price,
			        'url' => $val->url(),
			        'posted' => date('j M Y', $val->posted_at),
			        'location' => $location,
			        'sold'=> $sold,
			    );
			}
			//echo "<pre>";print_r($res);echo "</pre>";
		}
		/*{
			foreach ($list as $bmk) 
			{
				$item = $bmk->listing;
				if (empty($item) || empty($item->id)) 
					continue;
				$count++;
				
				$arr_bmk = array_merge($arr_bmk, array($item->id));
			}
			$this->view->count = $count;
			
			$lists = Model_Listing::all(array('id' => array('$in' => $arr_bmk)))->limit(10)->sort($sort)->skip(($page-1)*10);
			//$lists = Model_Listing::all(array('id' => array('$in' => $arr_bmk)))->limit(10)->sort(array('pr'=>-1))->skip(($page-1)*10);
			//$lists = Model_Listing::all(array('id' => array('$in' => $arr_bmk)))->limit(10)->sort(array('pr'=>-1, 'sp'=>-1, 'rp'=>-1 ))->skip(($page-1)*10);
			foreach($lists as $val)
			{
				//echo "<br>".$val->id." ".date('j M Y', $val->posted_at)." ".$val->price." ".$val->url();
				
				//Define the price value
			    $price = '';
			    $price1 = "";
			    $price2 = "";
			    $location = "";
			    if (!empty($val->sale_price) || !empty($val->rent_price)){
			        if (!empty($val->sale_price)) {
			            $sale_price = number_format($val->sale_price);
			            $price1 = "<dd>HKD ".$sale_price."<em>(Sale)</em></dd>";
			        }
			        if (!empty($val->rent_price)) {
			            $rent_price = number_format($val->rent_price);
			            $price2 = "<dd>HKD ".$rent_price."<em>(Rent)</em></dd>";
			        }
			        $price = $price1.' '.$price2;
			    }
			    elseif (!empty($val->is_free)){
			        $price = 'Free';
			    }
			    elseif (!empty($val->is_contact)){
			        $price = 'Please contact';
			    }
			    elseif (!empty($val->price)){
			        $price = 'HKD '.number_format($val->price);
			    }
				if(!empty($val->district))
					$location = $val->district;
					
			    $res[] = array(
			        'id' => (string) $val->_id,
			        'url' => $val->url(),
			        'title' => $val->title,
			        'photo' => $this->view->thumbnail()->scale($val->featured_photo, 80, 80),
			        //'price' => 'HKD '.number_format($listing->price),
			        'price' => $price,
			        'url' => $val->url(),
			        'posted' => date('j M Y', $val->posted_at),
			        'location' => $location,
			        //'count'=> $list->count(),
			    );
			}
		
		}*/
		
		
		return $res;
		
	}
	
    /**
     *
     */
    public function loginAction()
    {
       $this->_helper->_layout->setLayout('layout-mobile2');
       $form = new User_Form_LoginMobileForm();
       $mobilespace = new Zend_Session_Namespace('Mobile');
       //echo (empty($mobilespace->bookmarkID))?$mobilespace->bookmarkID:"EMPTY";
       //$to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
       $this->view->err_login = false;
       if ($this->_request->isPost() && $form->isValid($_POST['login'])) {
           $user = new Model_User();
           $form->setUser($user);
           try {
               if($form->save()) {
               		
               		if(!empty($mobilespace->bookmarkID))
               		{
						Model_Bookmark::addListing($mobilespace->bookmarkID);
						$mobilespace->bookmarkID = '';
						$this->_redirect($this->view->geturl('saved', 'user'));
					}
					if(!empty($mobilespace->removeBookmarkID))
               		{
						Model_Bookmark::remove(array('ls'=>$mobilespace->removeBookmarkID, 'us'=>Zend_Registry::get('loggedin_user')->_id));
						$mobilespace->removeBookmarkID = '';
						$this->_redirect($this->view->geturl('saved', 'user'));
					}
                    if (!empty($mobilespace->back_url)) {
                        $url = $mobilespace->back_url;      
						if(!empty($mobilespace->back_url2)){
							$url = $mobilespace->back_url2;
						}                  	
                        $mobilespace->unsetAll();
                        if(strpos($url, '/login')===false) {
                        	$this->_redirect($url);
                        } else {
                        	$this->_redirect('/');
                        }
                    } else {
                    	$mobilespace->unsetAll();
                        $this->_redirect('/');
                    }
               }
               throw new Ac_User_Behavior_Exception('Credential incorrect');
           }  catch (Ac_User_Behavior_Exception $e) {
               //Exception should come from behavior class not the exception above
               echo "Catched!";
               $this->view->err_login = true;
               $form->addError($e->getMessage());
           }
       }
       $this->view->form_login = $form;
    }


    public function registerPostAdAction()
    {
       $this->_helper->_layout->setLayout('register-postad-layout');
       $form1 = new User_Form_LoginMobileForm();
       $form2 = new User_Form_RegisterPersonalForm();

       
       $this->view->form_login = $form1;
       $this->view->form_register = $form2;
    }

    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('/');
    }

    public function twitterAction()
    {
       $user = new Model_User();
       $user->setBehavior(new Ac_User_Behavior_Twitter($this->view->geturl('twitter','user')));
       $user->login();
       if (Zend_Auth::getInstance()->hasIdentity()) {
           $this->_redirect($this->view->geturl('post-registration', 'user', null, null, array('type' => 'twitter')));
       }
    }

    public function facebookAction()
    {
       $user = new Model_User();
       $user->setBehavior(new Ac_User_Behavior_Facebook($this->view->geturl('facebook','user')));
       $user->login();
       if (Zend_Auth::getInstance()->hasIdentity()) {
           $this->_redirect($this->view->geturl('post-registration', 'user', null, null, array('type' => 'facebook')));
       }
    }

    public function registerAction()
    {
        $this->_helper->_layout->setLayout('login-layout');
        $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
        
        //echo '<pre>';print_r($_SESSION);
        //print_r($to_be_confirmed_ads);exit;
        
        //Personal account
        $form = new User_Form_RegisterPersonalForm();
        if ($this->_request->isPost() && $_POST['newaccount']['type'] == 'personal' && $form->isValid($_POST['newaccount'])) {
           $user = new Model_User();
           $form->setUser($user);
           try {
               if($form->save()) {
                   $this->_redirect($this->view->geturl('post-registration-post-an-ad', 'user', null, null, array('personal' => 1, 'return'=> (string) $ad->_id)));
               }
               throw new Ac_User_Behavior_Exception('Credential incorrect');
           }  catch (Ac_User_Behavior_Exception $e) {
               //Exception should come from behavior class not the exception above
               $form->addError($e->getMessage());
           }
       }
       $this->view->form_register_personal = $form;
    }

    public function registerCompanyAction()
    {
       //Company account
       $this->_helper->_layout->setLayout('register-layout');
       $form = new User_Form_RegisterCompanyForm();
       if ($this->_request->isPost() && $_POST['personal']['type'] == 'company' && $form->isValid($_POST)) {
           $user = new Model_User();           
           $form->setUser($user);           
           try {
               if($form->save()) {                   
                   $this->_redirect($this->view->geturl('post-registration-post-an-ad', 'user', null, null, array('return'=> (string) $ad->_id)));
               }
               throw new Ac_User_Behavior_Exception('Credential incorrect');
           }  catch (Ac_User_Behavior_Exception $e) {
               //Exception should come from behavior class not the exception above
               $form->addError($e->getMessage());
           }
       }
       $this->view->form_register_company = $form;        
    }

    public function validateRegisterPersonalAction()
    {
       $form = new User_Form_RegisterPersonalForm();
       unset($_POST['newaccount']['captcha']);
       $form->isValidPartial($_POST);
       $this->_helper->json($form->getMessages());
    }

    public function validateRegisterCompanyAction()
    {
       $form = new User_Form_RegisterCompanyForm();
       unset($_POST['personal']['captcha']);
       $form->isValidPartial($_POST);
       $this->_helper->json($form->getMessages());
    }

    public function confirmProfilePicAction()
    {
        $this->loggedin_user->profile_picture = $_POST['url'];
        $this->loggedin_user->save();
        $this->_helper->json(array('result' => '1'));
    }

    public function confirmCompanyPicAction()
    {
        if ($this->loggedin_user->type_account & Model_User::COMPANY_ADMIN) {
            $company = $this->loggedin_user->company;
            $company->image = $_POST['url'];
            $company->save();
            $this->_helper->json(array('result' => '1'));
        }
        $this->_helper->json(array('result' => '0'));
    }

    public function postRegistrationAction()
    {
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            if ($this->_request->isGet() && !$this->_request->isXmlHttpRequest()) {
                $session = new Zend_Session_Namespace('previous_page');
                $session->url = $_SERVER['REQUEST_URI'];
            }
            $this->_redirect($this->view->geturl('login', 'user'));
        }        
        $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
        //echo '<pre>';print_r($_SESSION);
        //print_r((array)$to_be_confirmed_ads->arr);exit;
        $arr = (array) $to_be_confirmed_ads->arr;
        //var_dump($arr);exit;
        if (!empty($arr)) {
            $to_add = null;
            if (!empty($_GET['type'])) {
                $to_add[$_GET['type']] = 1;
            }
            $this->_redirect($this->view->geturl('post-registration-post-an-ad', 'user', null, null, $to_add));
            return;
        }

        if (strpos($this->loggedin_user->email, 'gmail.com')) {
            $this->view->email_url = 'http://gmail.com';
        } elseif (strpos($this->loggedin_user->email, 'hotmail.com')) {
            $this->view->email_url = 'http://hotmail.com';
        }
        if (empty($this->loggedin_user->cid)) {
            $this->render('post-registration-personal');
        } else {
            $this->render('post-registration-company');
        }
    }


    public function postRegistrationPostAnAdAction()
    {
        
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            if ($this->_request->isGet() && !$this->_request->isXmlHttpRequest()) {
                $session = new Zend_Session_Namespace('previous_page');
                $session->url = $_SERVER['REQUEST_URI'];
            }
            $this->_redirect($this->view->geturl('login', 'user'));
        }        
        //echo '<pre>';print_r($_SESSION);exit;
        $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
        $arr = (array) $to_be_confirmed_ads->arr;
        //if (empty($arr)) {
        //    $this->_redirect($this->view->geturl('post-registration', 'user'));
        //}

        // action body
        // créons un nouvel e-mail
        //$mail = new Ac_Mail();
        //$mail->setSubject($this->view->t('Message subject'));

        // on spécifie le titre qu'on affichera dans le layout
        //$mail->title = $this->view->t('Message title');

        // on spécifie les scripts à utiliser pour la vue
        //$mail->setScriptText('new-user.text', 'user');
        //$mail->setScriptHtml('new-user.html', 'user');

        // on envoi le tout au webmaster
        //$mail->setFrom($config->mail->webmaster, 'Webmaster');
        //$mail->setFromConfig(AC_Mail::WEBMASTER);
        //$mail->setTo('olivier@olivier-desktop');
        //$mail->send(true);

        $ads = array();
        foreach ($arr as $ad_id) {
            $ad = Model_Listing::find($ad_id);
            if (!empty($ad)) {
                $ad->status = Model_Listing::STATUS_PUBLISHED;
                $ad->user = $this->loggedin_user->_id;
                $category_list = array();

                //Save the previous list of categories
                foreach($ad->category as $cat) {
                    $category_list[] = $cat;
                }

                $ad->category = array();
      
                //Change the category of the Ad for Car, Motorcycle and Boat
                foreach($category_list as $cat) {
                    //Car
                    if ($cat->nm_en == 'Car for Sale')        {
                        if ($ad->user->type_account == Model_User::PERSONAL)        {
                            $data = Model_Category::one(array('id' => 'c464'));
                            $ad->addCategory($data->_id);
                        }
                        elseif (($ad->user->type_account == Model_User::AGENT) || ($ad->user->type_account == Model_User::COMPANY_ADMIN))       {
                            $data = Model_Category::one(array('id' => 'c458'));
                            $ad->addCategory($data->_id);
                        }
                    }
                    //Boat
                    elseif ($cat->nm_en == 'Boat for Sale')        {
                        if ($ad->user->type_account == Model_User::PERSONAL)        {
                            $data = Model_Category::one(array('id' => 'c460'));
                            $ad->addCategory($data->_id);
                        }
                        elseif (($ad->user->type_account == Model_User::AGENT) || ($ad->user->type_account == Model_User::COMPANY_ADMIN))       {
                            $data = Model_Category::one(array('id' => 'c594'));
                            $ad->addCategory($data->_id);
                        }
                    }
                    //Motorcycle
                    elseif ($cat->nm_en == 'Motorcycle for Sale')        {
                        if ($ad->user->type_account == Model_User::PERSONAL)        {
                            $data = Model_Category::one(array('id' => 'c581'));
                            $ad->addCategory($data->_id);
                        }
                        elseif (($ad->user->type_account == Model_User::AGENT) || ($ad->user->type_account == Model_User::COMPANY_ADMIN))       {
                            $data = Model_Category::one(array('id' => 'c582'));
                            $ad->addCategory($data->_id);
                        }
                    }
                    //Other Categories
                    else {
                        $ad->addCategory($cat->_id);
                    }
                }                

                $ad->save();
                //echo $ad->_id.'<br>';
                $ads[] = $ad;
            }
        }

        $to_be_confirmed_ads->unlock();
        unset($to_be_confirmed_ads->arr);
        $this->view->ads_activated = $ads;

        if(!empty($_GET['login_process'])) {
            $this->view->login_process = 1;
        }


        if (strpos($this->loggedin_user->email, 'gmail.com')) {
            $this->view->email_url = 'http://gmail.com';
        } elseif (strpos($this->loggedin_user->email, 'hotmail.com')) {
            $this->view->email_url = 'http://hotmail.com';
        }

        if (empty($this->loggedin_user->cid)) {
            //Sign up Process
            if (empty($arr)) {
                $this->render('post-registration-personal');
            }
            else {
                $this->render('post-registration-post-an-ad-personal');                
            }
        } else {
            //Sign up Process
            if (empty($arr)) {
                $this->render('post-registration-company');
            }
            else {
                $this->render('post-registration-post-an-ad-company');
            }            
        }
    }

    public function completeLoginAction()
    {
        $user = $this->loggedin_user;
        if (!$user->isProfileComplete()) {
            $form = new User_Form_CompleteProfileForm(array('initialize' => false));
            $form->setUser($user);
            $form->init();
            if ($this->_request->isPost() && $form->isValid($_POST)) {
                $form->save();
                $this->_redirect($this->view->geturl('my-account', 'user'));
            }
            $this->view->form = $form;
        } else {

            $this->_redirect($this->view->geturl('my-account', 'user'));
        }
    }

    public function myAccountAction()
    {
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            if ($this->_request->isGet() && !$this->_request->isXmlHttpRequest()) {
                $session = new Zend_Session_Namespace('previous_page');
                $session->url = $_SERVER['REQUEST_URI'];
            }
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->_helper->_layout->setLayout('layout');

        $this->addTitle('My account');
        $this->addTitle('account Admin');

        if (strpos($this->loggedin_user->email, 'gmail.com')) {
            $this->view->email_url = 'http://gmail.com';
        } elseif (strpos($this->loggedin_user->email, 'hotmail.com')) {
            $this->view->email_url = 'http://hotmail.com';
        }

        //$this->view->getNoPublishedAds = $this->loggedin_user->getNoPublishedAds();
        $this->view->getNoViews = $this->loggedin_user->getNoViews();
        $this->view->getNoShares = $this->loggedin_user->getNoShares();
        $this->view->getNoResponses = $this->loggedin_user->getNoResponses();
        $this->view->subAccounts = '7';
    }

    public function forgetPasswordAction()
    {
        $this->_helper->_layout->setLayout('login-layout');
        $form = new User_Form_ForgetPasswordForm();
        if ($this->_request->isPost() && $form->isValid($_POST)) {
            $form->save();
            $this->view->success = true;
        }
        $this->view->form = $form;
        $this->render('forget-password');
    }

    public function validateForgetPasswordAction()
    {
        $form = new User_Form_ForgetPasswordForm();
        $form->isValidPartial($_POST);
        $this->_helper->json($form->getMessages());
    }
    
    public function myAccountAdsAction()
    {
        if ($this->_request->isPost()) {
            //echo "<PRE>"; print_r($_POST);exit;
            //define which action has been selected
            if (!empty($_POST['action1']) || !empty($_POST['action2'])) {
                if (!empty($_POST['action1'])) {
                    $action = $_POST['action1'];
                } elseif (!empty($_POST['action2'])) {
                    $action = $_POST['action2'];
                }

                foreach($_POST['chk'] as $id) {
                    $ad = Model_Listing::find($id);
                    if($action == 'renew') {
                        $ad->renew();
                    } elseif($action == 'publish') {
                        $ad->publish();
                    } elseif($action == 'unpublish') {
                        $ad->unpublish();
                    } elseif($action == 'delete') {
                        $ad->deleteListing();
                    }
                }
            }
        }

        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }

        $sort      = !empty($_REQUEST['sort']) ? $_REQUEST['sort'] : 'recent';
        $page      = !empty($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        $per_page  = 10;
        $solr = Ac_Search::getClient();
        if (!empty($_REQUEST['search_text'])) {
            if($_REQUEST['search_type'] == 1){
                $query = 'description:'.$_POST['search_text'].' title:'.$_REQUEST['search_text'];
            } else {
                $query = 'title:'.$_POST['search_text'];
            }
        }
        elseif (!empty($_REQUEST['search_text2'])) {
            if($_REQUEST['search_type2'] == 1){
                $query = 'description:'.$_POST['search_text2'].' title:'.$_REQUEST['search_text2'];
            } else {
                $query = 'title:'.$_POST['search_text2'];
            }
        }
        else {
            $query = '*:*';
        }

        $start = ($page-1) * $per_page;

        $additionalParameters['fq'] = ' +user_id:'. (string) $this->loggedin_user->_id;
        if (!empty($_REQUEST['category'])) {
            $additionalParameters['fq'] .= ' +category:'.$_REQUEST['category'];
        }
        if (!empty($_REQUEST['location']) && $_REQUEST['location'] != '_empty_') {
            $additionalParameters['fq'] .= ' +area_l2:'.$_REQUEST['location'];
        }

        $date_filter = array(
            1 => 'Last 24 hours',
            2 => 'Last 7 days',
            3 => 'Last 14 days',
            4 => 'Last 30 days',
            5 => 'Last 60 days',
            6 => 'Last 90 days',
            7 => 'Last 180 days',
        );

        if (!empty($_REQUEST['post_date'])) {
            if ($_REQUEST['post_date'] == 1) {
                $date_st  = time()- 24*3600;
                $date_end  = time();
            } elseif ($_REQUEST['post_date'] == 2) {
                $date_st  = time()- 7*24*3600;
                $date_end  = time();
            } elseif ($_REQUEST['post_date'] == 3) {
                $date_st  = time()- 14*24*3600;
                $date_end  = time();
            } elseif ($_REQUEST['post_date'] == 4) {
                $date_st  = time()- 30*24*3600;
                $date_end  = time();
            } elseif ($_REQUEST['post_date'] == 5) {
                $date_st  = time()- 60*24*3600;
                $date_end  = time();
            } elseif ($_REQUEST['post_date'] == 6) {
                $date_st  = time()- 90*24*3600;
                $date_end  = time();
            } elseif ($_REQUEST['post_date'] == 7) {
                $date_st  = time()- 180*24*3600;
                $date_end  = time();
            }
            if ($_REQUEST['post_date'] == 1) {
                $start_dt = date('Y-m-d\TH:i:s\Z', $date_st);
                $end   = date('Y-m-d\TH:i:s\Z', $date_end);
            } else {
                $start_dt = date('Y-m-d\T00:00:00\Z', $date_st);
                $end   = date('Y-m-d\T23:59:59\Z', $date_end);
            }
            $additionalParameters['fq'] .= ' +posted_at:['.$start_dt.' TO '.$end.']';
        }

        $sort = '';
        if (!empty($_REQUEST['sort1'])) {
            $sort = $_REQUEST['sort1'];
        } elseif (!empty($_REQUEST['sort2'])) {
            $sort = $_REQUEST['sort2'];
        }
        
        switch ($sort) {
            case 'high':
                $sort = 'price desc';
                $_REQUEST['sort1'] = 'high';
                $_REQUEST['sort2'] = 'high';
                break;
            case 'views':
                $sort = 'views desc';
                $_REQUEST['sort1'] = 'views';
                $_REQUEST['sort2'] = 'views';

                break;
            case 'low':
                $sort = 'is_free asc, price asc';
                $_REQUEST['sort1'] = 'low';
                $_REQUEST['sort2'] = 'low';
                break;
            case 'rel':
                $sort = 'score desc';
                $_REQUEST['sort1'] = 'rel';
                $_REQUEST['sort2'] = 'rel';
                break;
            case 'title':
                $sort = 'title_sort asc';
                $_REQUEST['sort1'] = 'title';
                $_REQUEST['sort2'] = 'title';
                break;
            default:
            case 'recent':
                $sort = 'posted_at desc';
                $_REQUEST['sort1'] = 'recent';
                $_REQUEST['sort2'] = 'recent';
                break;
        }
        $additionalParameters['sort'] = $sort;

        if(empty($_REQUEST['tab']) || $_REQUEST['tab'] == Model_Listing::STATUS_PUBLISHED) {
            $this->view->tab = Model_Listing::STATUS_PUBLISHED;
            $additionalParameters['fq'] .= ' +status:'.Model_Listing::STATUS_PUBLISHED;
        } else {
            $this->view->tab = Model_Listing::STATUS_DRAFT;
            $additionalParameters['fq'] .= ' +status:'.Model_Listing::STATUS_DRAFT;
        }

        if (DISPLAY_DEBUG) {
            echo "<PRE style='clear:both'>"; print_r($_REQUEST);print_r($additionalParameters);echo "</PRE>";
        }

        $list = $solr->search($query, $start, $per_page, $additionalParameters);


        
        // filter lists
        $additionalParameters = array(
            'facet'          => 'true',
            'facet.mincount' => '1',
            'facet.field'    => array('category_attached', 'area_l2'),
            'fq'             =>'+user_id:'. (string) $this->loggedin_user->_id);

        if(empty($_REQUEST['tab']) || $_REQUEST['tab'] == Model_Listing::STATUS_PUBLISHED) {
            $additionalParameters['fq'] .= ' +status:'.Model_Listing::STATUS_PUBLISHED;
        } else {
            $additionalParameters['fq'] .= ' +status:'.Model_Listing::STATUS_DRAFT;
        }

        $list_facet = $solr->search('*:*', $start, $per_page, $additionalParameters);

        /*echo '<pre style="clear:both">';
        print_r($_REQUEST);
        print_r($additionalParameters);
        print_r($list_facet->facet_counts->facet_fields);
        echo '</pre>';*/

        // tab count
        $additionalParameters = array(
            'facet'          => 'true',
            'facet.field'    => array('status'),
            'facet.mincount' => '1',
            'facet.query'    => array('status:[* TO 1]', 'status:[2 TO 3]'),
            'fq'             =>'+user_id:'. (string) $this->loggedin_user->_id);

        $list_tab = $solr->search('*:*', $start, $per_page, $additionalParameters);

        
        $tabs = array(
            Model_Listing::STATUS_PUBLISHED => $list_tab->facet_counts->facet_queries->{'status:[* TO 1]'},
            Model_Listing::STATUS_DRAFT => $list_tab->facet_counts->facet_queries->{'status:[2 TO 3]'},
        );

        $this->view->list_filter    = $list_facet->facet_counts->facet_fields;
        $this->view->list_filter_date = $date_filter;
        $this->view->tabs           = $tabs;
        $this->view->list           = $list->response->docs;
        $this->view->listing_number = $list->response->numFound;
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;

        $this->addTitle('Ads');
    }
    public function showMySubaccountsAction(){
        $this->addTitle('My sub accounts');
    }

    public function myAccountProfileAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
            if (!empty($_POST['firstname'])) {
                $this->loggedin_user->firstname = $_POST['firstname'];
            }
            else {
                if (isset($_POST['firstname'])) {
                    $this->loggedin_user->firstname = '';
                }
            }
            if (!empty($_POST['lastname'])) {
                $this->loggedin_user->lastname = $_POST['lastname'];
            }
            else {
                if (isset($_POST['lastname'])) {
                    $this->loggedin_user->lastname = '';
                }
            }
            if (!empty($_POST['username'])) {
                //Checking if Username Already exists
                $user = Model_User::one(array('username' => $_POST['username']));
                if (empty($user)) {
                    $this->loggedin_user->username = $_POST['username'];
                    echo 'ok';exit;
                }
                else {
                    if ($this->loggedin_user->username == $_POST['username']) {
                        echo 'ok';exit;
                    }
                    else { echo 'nok';exit; }
                }                
            }
            if (!empty($_POST['phone'])) {
                $this->loggedin_user->phone = $_POST['phone'];
            }
            else {
                if (isset($_POST['phone'])) {
                    $this->loggedin_user->phone = '';
                }
            }
            if (!empty($_POST['license'])) {
                $this->loggedin_user->license_id = $_POST['license'];
            }
            else {
                if (isset($_POST['license'])) {
                    $this->loggedin_user->license_id = '';
                }
            }

            $this->loggedin_user->save();
            echo 'ok';exit;
        }
        
        $_GET['type'] = empty($_GET['type']) ? '' : $_GET['type'];
        if ($_GET['type'] != 'holder' && $this->loggedin_user->type_account & Model_User::COMPANY_ADMIN) {
            $this->render('my-account-company-profile');
        } elseif ($_GET['type'] == 'holder' || $this->loggedin_user->type_account & Model_User::AGENT) {
            $this->render('my-account-company-profile-holder');
        } else {
            $this->render('my-account-profile');
        }
    }

    public function accountHolderPhoneAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
            if (!empty($_POST['phone'])) {
                $this->loggedin_user->phone = $_POST['phone'];
            }
            else  { unset($this->loggedin_user->phone); }

            $this->loggedin_user->save();
            echo 'ok';exit;
        }        
    }
    
    public function accountHolderLicenseAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
            if (!empty($_POST['license'])) {
                $this->loggedin_user->license_id = $_POST['license'];
            }
            else  { unset($this->loggedin_user->license_id); }

            $this->loggedin_user->save();
            echo 'ok';exit;
        }
    }

    public function accountHolderServicesAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
            if (!empty($_POST['services'])) {
                $this->loggedin_user->services = $_POST['services'];
            }
            else  { unset($this->loggedin_user->services); }

            $this->loggedin_user->save();
            echo 'ok';exit;
        }
    }
    
    public function myAccountAccountAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My account');
        if($this->_request->isPost()) {
            //Change the password
            if ((!empty($_POST['old_password'])) && (!empty($_POST['password'])) && (!empty($_POST['password_conf']))) {
                //Check the old password
                if ($this->loggedin_user->password != Model_User::generatePassword($_POST['old_password'])) {
                    //$this->loggedin_user->password = Model_User::generatePassword($_POST['password']);
                    //$this->loggedin_user->save();
                    //print_r($this->loggedin_user->password.' '.Model_User::generatePassword($_POST['old_password']));exit;
                    echo 'nok';exit;
                } else {
                    $this->loggedin_user->password = Model_User::generatePassword($_POST['password']);
                    $this->loggedin_user->save();
                    echo 'ok';exit;
                }              
            }


            //Change the language
            if (!empty($_POST['profile_language'])) {
                $this->loggedin_user->language = $_POST['profile_language'];
                $this->loggedin_user->save();
                echo 'ok';exit;
            }            
            echo 'ok';exit;
        }
    }

    public function newsletterAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My account');
        if($this->_request->isPost()) {
            //Change the notification for Newsletters
            if (!empty($_POST['notif_newsletter'])) {
                $this->loggedin_user->newsletter = '1';
                echo $_POST['notif_newsletter'];exit;
            }
            else {
                $this->loggedin_user->newsletter = '0';
            }
            $this->loggedin_user->save();
            echo 'ok';exit;
        }            
    }

    public function validEmailAction(){
        if($this->_request->isPost()) {
            if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['email'])) {
                echo 'ok';
            }
            else {
                echo 'nok';
            }
            exit;
        }
    }

    public function newsletterSubscribeAction(){
        //If the user is logged
        if($this->_request->isPost()) {
            $user = Model_User::one(array('email' => $_POST['email']));
            $exist = false;
            //If User is logged in
            if(!empty($this->loggedin_user)){
                //User already loggedin
                $user = $this->loggedin_user;
            }
            //If user is not logged in but the email already exists
            elseif (!empty($user))
            {
                $exist = true;
            }
            //If user is not logged in and the email does not exist
            else {
                //New user
                $user = new Model_User();
                $user->email = $_POST['email'];
                $user->username = Model_User::generateUsername($_POST['email']);
                $user->password = Model_User::generatePassword($_POST['email']);
            }
            $user->newsletter = '1';
            $user->save();
            $session = new Zend_Session_Namespace('newsletter');
            $session->email = $user->email;
            if ($exist) { $session->exist = true; } else { $session->exist = false; }
            //Redirection to the success page for Loggedin User
            $this->_redirect($this->view->geturl('newsletter-subscribe', 'user'));
        }
        $session = new Zend_Session_Namespace('newsletter');
        $this->view->email = $session->email;
        $this->view->exist = $session->exist;
        $this->render('newsletter-subscribe-success');
    }

    public function myCompanyProfileAction(){
        if($this->_request->isPost()) {
            if(empty($this->loggedin_user) || !$this->loggedin_user->type_account & Model_User::COMPANY_ADMIN){
                //raise an exception
                //throw new Exception("Must be logged in to access User Dashboard");
                $this->_redirect($this->view->geturl('login', 'user'));
            }
            $company = $this->loggedin_user->company;
            if (!empty($_POST['company_name'])) {
                $company->company_name = $_POST['company_name'];
            }
            if (!empty($_POST['mailing_address'])) {
                $company->mailing_address = $_POST['mailing_address'];
            }
            else  { unset($company->mailing_address); }
            if (!empty($_POST['website'])) {
                $company->website = $_POST['website'];
            }
            else  { unset($company->website); }
            if (!empty($_POST['phone'])) {
                $company->phone = $_POST['phone'];
            }
            if (!empty($_POST['number_employees'])) {
                $company->number_employees = $_POST['number_employees'];
            }
            else  { unset($company->number_employees); }
            if (!empty($_POST['location'])) {
                $company->location = $_POST['location'];
            }
            else  { unset($company->location); }
            if (!empty($_POST['fax'])) {
                $company->fax = $_POST['fax'];
            }
            else  { unset($company->fax); }
            if (!empty($_POST['facebook_twitter'])) {
                $company->facebook_twitter = $_POST['facebook_twitter'];
            }
            else  { unset($company->facebook_twitter); }
            if (!empty($_POST['backlink'])) {
                $company->backlink = $_POST['backlink'];
            }
            else  { unset($company->backlink); }
            if (!empty($_POST['business_category'])) {
                $company->business_category = $_POST['business_category'];
            }

            $company->save();
            echo 'ok';exit;
        }
    }

    public function contactInformationAction(){
        if($this->_request->isPost()) {
            if(empty($this->loggedin_user) || !$this->loggedin_user->type_account & Model_User::COMPANY_ADMIN){
                //raise an exception
                //throw new Exception("Must be logged in to access User Dashboard");
                $this->_redirect($this->view->geturl('login', 'user'));
            }
            $company = $this->loggedin_user->company;
            if (!empty($_POST['contact_firstname'])) {
                $company->contact_firstname = $_POST['contact_firstname'];
            }
            else  { unset($company->contact_firstname); }
            if (!empty($_POST['contact_lastname'])) {
                $company->contact_lastname = $_POST['contact_lastname'];
            }
            else  { unset($company->contact_lastname); }
            if (!empty($_POST['contact_job'])) {
                $company->contact_job = $_POST['contact_job'];
            }
            else  { unset($company->contact_job); }
            if (!empty($_POST['contact_department'])) {
                $company->contact_department = $_POST['contact_department'];
            }
            else  { unset($company->contact_department); }
            if (!empty($_POST['contact_phone'])) {
                $company->contact_phone = $_POST['contact_phone'];
            }
            else  { unset($company->contact_phone); }
            if (!empty($_POST['contact_email'])) {
                $company->contact_email = $_POST['contact_email'];
            }
            else  { unset($company->contact_email); }

            $company->save();
            echo 'ok';exit;
        }
    }

    public function aboutUsAction(){
        if($this->_request->isPost()) {
            if(empty($this->loggedin_user) || !$this->loggedin_user->type_account & Model_User::COMPANY_ADMIN){
                //raise an exception
                //throw new Exception("Must be logged in to access User Dashboard");
                $this->_redirect($this->view->geturl('login', 'user'));
            }
            $company = $this->loggedin_user->company;
            if (!empty($_POST['about'])) {
                $company->about = $_POST['about'];
            }
            else  { unset($company->about); }
            
            $company->save();
            echo 'ok';exit;
        }
    }

    public function myDraftAdsAction(){
        $this->addTitle('My draftAds');
    }
    public function addSubaccountAction(){
        $this->addTitle('addSubaccount');
    }

    /**
     * Display user public profile
     * Should choose different views based on the type of user
     */
    public function displayAction()
    {
        $user = Model_User::one(array('username' => $this->_request->getParam('username')));

        if ($user == null) {// user not found
            throw new Ac_Exception_MissingUser();
        }

        $this->addTitle($user->username);        
        
        //search for listings
        $sort      = !empty($_GET['sort']) ? $_GET['sort'] : 'recent';
        $page      = !empty($_GET['page']) ? $_GET['page'] : 1;
        $per_page  = 10;
        $solr = Ac_Search::getClient();
        if (!empty($_GET['search_text'])) {
            if($_GET['search_type'] == 1){
                $query = 'description:'.$_GET['search_text'].' title:'.$_GET['search_text'];
            } else {
                $query = 'title:'.$_GET['search_text'];
            }
        }
        elseif (!empty($_GET['search_text2'])) {
            if($_GET['search_type2'] == 1){
                $query = 'description:'.$_GET['search_text2'].' title:'.$_GET['search_text2'];
            } else {
                $query = 'title:'.$_GET['search_text2'];
            }
        }
        else {
            $query = '*:*';
        }

        $start = ($page-1) * $per_page;
        
        $additionalParameters['fq'] = '+status: '.Model_Listing::STATUS_PUBLISHED.' +user_id:'. (string) $user->_id;

        /*$sort = '';
        if (!empty($_REQUEST['sort1'])) {
            $sort = $_REQUEST['sort1'];
        } elseif (!empty($_REQUEST['sort2'])) {
            $sort = $_REQUEST['sort2'];
        }*/

        switch ($sort) {
            case 'high':
                $sort = 'price desc';
                $_REQUEST['sort1'] = 'high';
                $_REQUEST['sort2'] = 'high';
                break;
            case 'views':
                $sort = 'views desc';
                $_REQUEST['sort1'] = 'views';
                $_REQUEST['sort2'] = 'views';

                break;
            case 'low':
                $sort = 'is_free asc, price asc';
                $_REQUEST['sort1'] = 'low';
                $_REQUEST['sort2'] = 'low';
                break;
            case 'rel':
                $sort = 'score desc';
                $_REQUEST['sort1'] = 'rel';
                $_REQUEST['sort2'] = 'rel';
                break;
            case 'title':
                $sort = 'title_sort asc';
                $_REQUEST['sort1'] = 'title';
                $_REQUEST['sort2'] = 'title';
                break;
            default:
                $sort = 'posted_at desc';
                $_REQUEST['sort1'] = 'recent';
                $_REQUEST['sort2'] = 'recent';
                break;
        }
        $additionalParameters['sort'] = $sort;

        if (DISPLAY_DEBUG) {
            echo "<PRE style='clear:both'>"; print_r($_REQUEST);print_r($additionalParameters);echo "</PRE>";
        }
        
        $list = $solr->search($query, $start, $per_page, $additionalParameters);

		$user->number_views = $user->getNoViews() + 1;

        $this->view->user = $user;
        $this->view->list           = $list->response->docs;
        $this->view->listing_number = $list->response->numFound;
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;
		
		$user->save();
        //load bookmark
        $list = Model_Bookmark::getList();
        $bookmark = array();
        foreach($list as $bmk) {
            $bookmark[] = (string) $bmk->listing->_id;
        }
        $this->view->bookmark = $bookmark;

        if ($user->type & Model_User::AGENT) {
            //$this->view->company = $user->company;
            //$this->render('display-company');
        } else {
            //$this->render('display-personal');
        }
        $this->_helper->_layout->setLayout('layout-mobile2');
        $this->render('profile-personal');
    }


    /**
     * Display user public profile
     * Should choose different views based on the type of user
     */
    public function displayCompanyAction()
    {
        $company = Model_Company::one(array('username' => $this->_request->getParam('company')));
        
        if ($company == null) {// user not found
            throw new Ac_Exception_MissingUser();
        }

        $this->addTitle($company->username);

        //search for listings
        $sort      = !empty($_GET['sort']) ? $_GET['sort'] : 'recent';
        $page      = !empty($_GET['page']) ? $_GET['page'] : 1;
        $per_page  = 10;
        $solr = Ac_Search::getClient();
        if (!empty($_GET['search_text'])) {
            if($_GET['search_type'] == 1){
                $query = 'description:'.$_GET['search_text'].' title:'.$_GET['search_text'];
            } else {
                $query = 'title:'.$_GET['search_text'];
            }
        }
        elseif (!empty($_GET['search_text2'])) {
            if($_GET['search_type2'] == 1){
                $query = 'description:'.$_GET['search_text2'].' title:'.$_GET['search_text2'];
            } else {
                $query = 'title:'.$_GET['search_text2'];
            }
        }
        else {
            $query = '*:*';
        }

        $start = ($page-1) * $per_page;

        $additionalParameters['fq'] = '+company_id:'. (string) $company->_id;
        $additionalParameters['fq'] .= ' +status:1 ';

        /*$sort = '';
        if (!empty($_REQUEST['sort1'])) {
            $sort = $_REQUEST['sort1'];
        } elseif (!empty($_REQUEST['sort2'])) {
            $sort = $_REQUEST['sort2'];
        }*/

        switch ($sort) {
            case 'high':
                $sort = 'price desc';
                $_REQUEST['sort1'] = 'high';
                $_REQUEST['sort2'] = 'high';
                break;
            case 'views':
                $sort = 'views desc';
                $_REQUEST['sort1'] = 'views';
                $_REQUEST['sort2'] = 'views';

                break;
            case 'low':
                $sort = 'is_free asc, price asc';
                $_REQUEST['sort1'] = 'low';
                $_REQUEST['sort2'] = 'low';
                break;
            case 'rel':
                $sort = 'score desc';
                $_REQUEST['sort1'] = 'rel';
                $_REQUEST['sort2'] = 'rel';
                break;
            case 'title':
                $sort = 'title_sort asc';
                $_REQUEST['sort1'] = 'title';
                $_REQUEST['sort2'] = 'title';
                break;
            default:
            case 'recent':
                $sort = 'posted_at desc';
                $_REQUEST['sort1'] = 'recent';
                $_REQUEST['sort2'] = 'recent';
                break;
        }
        $additionalParameters['sort'] = $sort;
        $list = $solr->search($query, $start, $per_page, $additionalParameters);
        
        if (DISPLAY_DEBUG) {
            echo '<pre>';print_r($additionalParameters);echo '</pre>';
            echo $list->response->numFound;
        }
        
        $company->number_views = $company->getNoViews() + 1;
        
        $this->view->company        = $company;
        $this->view->list           = $list->response->docs;
        $this->view->listing_number = $list->response->numFound;
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;
		
		$company->save();
		
        //load bookmark
        $list = Model_Bookmark::getList();
        if (!empty($list)) {
            $bookmark = array();
            foreach($list as $bmk) {
                $bookmark[] = (string) $bmk->listing->_id;
            }
            $this->view->bookmark = $bookmark;
        }

        $this->_helper->_layout->setLayout('layout-mobile2');
        $this->render('profile-company');
    }

    public function getBookmarkAction()
    {
        
		$page = empty($_GET['page'])?'1':$_GET['page'];
		$list = Model_Bookmark::getList();
		$count = 0;
		foreach ($list as $bmk) 
		{
			if (empty($bmk->listing)) 
				continue;
			$count++;
		}
		$this->view->count = $count;
		$list = Model_Bookmark::getList()->skip($page*10)->sort(array('created_at'=>-1));
		$count = 0;
		$res = array();
		foreach ($list as $bmk) {
		    $listing = $bmk->listing;
		    
		    if (empty($listing)) {
		        //$bmk->deleteListing();
		        continue;
		    }
		    $count++;
		    if ($count>10) {
		        break;
		    }
		    
		    //Define the price value
		    $price = '';
		    $price1 = "";
		    $price2 = "";
		    $location = "";
		    if (!empty($listing->sale_price) || !empty($listing->rent_price)){
		        if (!empty($listing->sale_price)) {
		            $sale_price = number_format($listing->sale_price);
		            $price1 = "<dd>HKD ".$sale_price."<em>(Sale)</em></dd>";
		        }
		        if (!empty($listing->rent_price)) {
		            $rent_price = number_format($listing->rent_price);
		            $price2 = "<dd>HKD ".$rent_price."<em>(Rent)</em></dd>";
		        }
		        $price = $price1.' '.$price2;
		    }
		    elseif (!empty($listing->is_free)){
		        $price = 'Free';
		    }
		    elseif (!empty($listing->is_contact)){
		        $price = 'Please contact';
		    }
		    elseif (!empty($listing->price)){
		        $price = 'HKD '.number_format($listing->price);
		    }
			if(!empty($listing->area_l2))
				$location = $listing->area_l2;
				
		    $res[] = array(
		        'id' => (string) $listing->_id,
		        'url' => $listing->url['0'],
		        'title' => $listing->title,
		        'photo' => $this->view->thumbnail()->scale($listing->featured_photo, 80, 80),
		        //'price' => 'HKD '.number_format($listing->price),
		        'price' => $price,
		        'url' => $listing->url(),
		        'posted' => date('j M Y', $listing->posted_at),
		        'location' => $location,
		        'count'=> $list->count(),
		    );
		}
		
		    return $res;
    }
    
    public function getHistoryAction()
    {
        $page = $_GET['page'];
        $list = Model_History::getList()->skip($page*6);

        $res = array();
        $count = 0;
        foreach($list as $bmk) {
            $listing = $bmk->listing;
            if (empty($listing)){
                $bmk->deleteListing();
                continue;
            }
            $count++;
            if ($count>6) {
                break;
            }

            //Define the price value
            $price = '';
            if (!empty($listing->sale_price) || !empty($listing->rent_price)){
                if (!empty($listing->sale_price)) {
                    $sale_price = number_format($listing->sale_price);
                    $price1 = "<dd>HKD ".$sale_price."<em>(Sale)</em></dd>";
                }
                if (!empty($listing->rent_price)) {
                    $rent_price = number_format($listing->rent_price);
                    $price2 = "<dd>HKD ".$rent_price."<em>(Rent)</em></dd>";
                }
                $price = $price1.' '.$price2;
            }
            elseif (!empty($listing->is_free)){
                $price = 'Free';
            }
            elseif (!empty($listing->is_contact)){
                $price = 'Please contact';
            }
            elseif (!empty($listing->price)){
                $price = 'HKD '.number_format($listing->price);
            }
            
            $res[] = array(
                'id' => (string) $listing->_id,
                'title' => $listing->title,
                'photo' => $this->view->thumbnail()->scale($listing->featured_photo, 65, 65),
                //'price' => 'HKD '.number_format($listing->price),
                'price' => $price,
                'url' => $listing->url(),
            );
        }
        $this->_helper->json(array('list' => $res, 'count' => $list->count()));
    }

    public function geocodeAction()
    {
        if ($this->_request->isPost()) {
            $company = Model_Company::find($_POST['id']);
            
            if (empty($company->latitude)) {
                $company->latitude = $_POST['latitude'];
            }
            if (empty($listing->longitude)) {
                $company->longitude = $_POST['longitude'];
            }
            $company->save();
        }
        exit;
    }
    
    public function verifyLoginAction()
    {
        $id = $_GET['id'];
        $u = Model_User::find($id);
        if ($u == null) {// user not found
            throw new Ac_Exception_MissingUser();
        }
        $u->verified = 1;
        $u->save();
        
        $this->_redirect($this->view->geturl('my-account', 'user', null, null, array('verified'=>1)));
    }
}
